import os
import uuid
import datetime
from django.http import FileResponse
from django.shortcuts import render, redirect, HttpResponse
from django.http import JsonResponse, Http404
from django.forms import model_to_dict
from django.views.decorators.csrf import csrf_exempt
from django.conf import settings
from web import models
from web.forms.file import FileModelForm
from utils import common
from utils.pagenation import Pagenation


# 文件列表页面
def file(request, project_id):
    # 如果获取到了父级目录
    parent_object = None
    folder_id = request.GET.get('folder', "")
    if folder_id.isdecimal():
        parent_object = models.FileRepository.objects.filter(id=int(folder_id), file_type=2,
                                                             project=request.tracer.project).first()
    #  GET 查看列表页面
    if request.method == "GET":
        # 获取面包屑导航数据
        data_breadcrumb = []
        parent = parent_object
        while parent:
            # breadcrumb_list.insert(0, {'id': parent.id, 'name': parent.name})
            data_breadcrumb.insert(0, model_to_dict(parent, ['id', 'name']))
            parent = parent.parent
        form = FileModelForm(request, parent_object)
        # 当前目录下所有的文件 & 文件夹   分页处理
        data_dict = {
            "project_id": project_id,
            "parent": parent_object
        }
        queryset = models.FileRepository.objects.filter(**data_dict).order_by('-file_type')
        page_object = Pagenation(request, queryset, 5)

        page_queryset = page_object.page_queryset
        page_string = page_object.html()

        # data_queryset = models.FileRepository.objects.filter(project_id=project_id, parent=parent_object).order_by('-file_type')

        return render(request, 'file.html', {
            'form': form,
            'data': page_queryset,
            'data_breadcrumb': data_breadcrumb,
            'folder_id': folder_id,
            "page_string": page_string,
        })
    #  POST 添加文件夹 & 文件夹的修改  的操作
    fid = request.POST.get("fid", "")
    if fid.isdecimal():
        # 编辑文件夹
        edit_object = models.FileRepository.objects.filter(id=fid, file_type=2, project=request.tracer.project).first()
        form = FileModelForm(request, parent_object, data=request.POST, instance=edit_object)

    else:
        # 新建文件夹
        form = FileModelForm(request, parent_object, data=request.POST)
    if form.is_valid():
        form.instance.project = request.tracer.project
        form.instance.file_type = 2
        form.instance.parent = parent_object
        form.instance.update_user = request.tracer.user
        form.save()
        return JsonResponse({'status': True})
    return JsonResponse({'status': False, 'error': form.errors})


# 文件上传
@csrf_exempt
def file_uploads(request, project_id):
    # 如果获取到了父级目录
    parent_object = None
    folder_id = request.POST.get('folder_id', "")
    if folder_id.isdecimal():
        parent_object = models.FileRepository.objects.filter(
            id=int(folder_id),
            file_type=2,
            project=request.tracer.project
        ).first()
    # 获取当前用户的价格策略
    # price_policy = request.tracer.price_policy
    # 获取POST提交过来的文件
    files_object = request.FILES.get('input-b9[]')
    if files_object:
        # 当前日期 20221215
        d_time = datetime.datetime.now().strftime('%Y%m%d')
        # 获取media的路径 D:\pythonProject\bugtracer\media\
        file_path = os.path.join(settings.FILES_DIR, d_time)
        # 如果没有则创建目录
        if not os.path.isdir(file_path):
            os.makedirs(file_path)
        # 获取文件的后缀
        suffix = files_object.name.rsplit(".", 1)[1]
        # 定义文件的存储key
        key = str(uuid.uuid4()) + '.' + suffix
        # 定义文件的路径
        path = os.path.join(d_time, key)
        # 价格策略---每项目空间大小，单位GB
        if request.tracer.project.used_size + files_object.size <= request.tracer.price_policy.space_size * 1024 * 1024 * 1024:
            try:
                # 保存文件到指定目录
                with open(os.path.join(file_path, key), 'w+b') as f:
                    # for i in files_object:
                    #     f.write(i)
                    for chunk in files_object.chunks():
                        f.write(chunk)
                # 写入数据库******************************************
                file = models.FileRepository.objects.create(
                    file_type=1,
                    name=files_object.name,
                    key=key,
                    file_size=files_object.size,
                    file_path=path,
                    parent=parent_object,
                    project=request.tracer.project,
                    update_user=request.tracer.user
                )
                # 项目的已使用空间：更新 (files_object.size)
                request.tracer.project.used_size += files_object.size
                request.tracer.project.save()
                data = {
                    # 'error': 'An error exception message if applicable',
                    'initialPreview': [],
                    'initialPreviewConfig': [],
                    'initialPreviewThumbTags': [],
                    'append': True
                }
                return JsonResponse(data)
            except Exception:
                data = {'error': '文件存储出错，请检查是否有足够的空间', }
                return JsonResponse(data)
        data = {'error': '空间不足', }
        return JsonResponse(data)

    data = {'error': '请选择需要上传的文件', }
    return JsonResponse(data)


# 文件下载
@csrf_exempt
def file_download(request, project_id, file_id):
    from django.utils.encoding import escape_uri_path
    # 获取当前app 即web的路径 D:\pythonProject\bugtracer\web
    file_dir = settings.FILES_DIR
    print(file_id)
    file_object = models.FileRepository.objects.filter(id=file_id, project=request.tracer.project).first()
    if file_object:
        try:
            f = os.path.join(file_dir, file_object.file_path)
            file = open(f, 'rb')
            response = FileResponse(file)
            # 提示浏览器保存文件
            response['Content-Type'] = 'application/octet-stream'
            # response['Content-Disposition'] = 'attachment;filename="{}"'.format(file_object.name.encode('utf-8').decode('ISO-8859-1'))
            # 设置响应头，escape_uri_path函数转义中文文件名
            response['Content-Disposition'] = 'attachment;filename="{}"'.format(escape_uri_path(file_object.name))
            print("文件存在=========")
            return response
        except FileNotFoundError:
            print("文件不存在********")
            data = {'status': False, 'errors': '文件不存在，或已被删除'}
            return JsonResponse(data)
            # raise Http404("文档不存在！")
            # raise e


def folder_edit(request, project_id, folder_id):
    folder_obj = models.FileRepository.objects.filter(project_id=project_id, id=folder_id).first()
    if folder_obj:
        data = folder_obj.name
        return JsonResponse({"status": True, "data": data})
    return JsonResponse({"status": False, "errors": '文件夹不存在，或已被删除'})


def file_delete(request, project_id):
    if request.method == "GET":
        print("删除文件or文件夹操作")
        # 获取ajax传递过来的fid
        fid = request.GET.get("fid", "")
        ftype = request.GET.get("ftype", "")
        delete_object = models.FileRepository.objects.filter(id=fid, project=request.tracer.project).first()
        if delete_object.file_type == 1:
            file_dir = settings.FILES_DIR
            f = os.path.join(file_dir, delete_object.file_path)
            try:
                print("***************")
                os.remove(f)
                delete_object.delete()
            except Exception as e:
                print("-------------")
                print(e)
                delete_object.delete()
            # 删除文件，将容量还给当前项目的已使用空间
            request.tracer.project.used_size -= delete_object.file_size
            request.tracer.project.save()
        else:
            del_list = common.deleteFolder(request, delete_object)
            for del_folder in del_list:
                del_folder.delete()
        return JsonResponse({"status": True})
    return JsonResponse({"status": False})
